-- AmazonAchievementM
-- Created by chengb Mar/1/2016
-- 亚马逊成就模块
-- 成就的进度更新、显示均由亚马逊的SDK负责管理

module("AmazonAchievementM", package.seeall);

local PURE_FILE = "AmazonAchievementM"

-- 成就配置表
local achievementTable = {};

-- 根据规则存放成就
local listByRule = {};

-- 所有子规则
local rules = {};

-- 成就进度更新请求队列
local requestQuene = {};

-- 请求处理间隔（秒）
local CHECK_INTERVAL = 1;

-- 提醒玩家登录Amazon账号的时间间隔（秒）
local REMIND_CD = 43200;

-- 内部函数声明
local appendRequest;
local checkRequest;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    achievementTable = {};

    amazon_achievement_CSV = get_amazon_achievement_CSV();
    for i = 1, #amazon_achievement_CSV do
        local id = amazon_achievement_CSV[i].id;
        achievementTable[id] = amazon_achievement_CSV[i];

        -- 根据规则存放
        local rule = amazon_achievement_CSV[i].rule;
        if listByRule[rule] == nil then
            listByRule[rule] = {};
        end
        table.insert(listByRule[rule], id);
    end

    amazon_achievement_CSV = {};
end

-- 初始化
function init()
    if not isFunctionOpen() then
        return;
    end

    if not _init then
        loadCsv();

        -- 载入所有的规则处理子模块g
        rules = LOAD_PATH("game/logic/module/amazon_achievement");
    end
end

-- 查询成就信息
function query(id, path)
    local m = achievementTable[id];

    if not m or path == "" or path == nil then
        return m;
    else
        return m[path];
    end
end

-- 根据规则获取成就id
function getIdsByRule(id)
    return listByRule[id] or {};
end

-- 功能是否开放
function isFunctionOpen()
    if PUBLISH_PLATFORM ~= PUBLISH_TYPE_AMAZON then
        return false;
    end

    return true;
end

-- 成就是否达成
function isCompleted(id)
    -- 注：amazon没有提供获取成就进度的接口，故默认未达成
    return false;
end

-- 更新成就进度
function tryComplete(id, count)
    local config = query(id);
    if not config then
        trace(PURE_FILE, "成就(%d)不存在。");
        return false;
    end

    if count <= 0 then
        trace(PURE_FILE, "成就步数(%d)非法。", count);
        return false;
    end

    -- 获取amazon控制台配置的编号
    local gid = config.gid;

    -- 如果当前未登录亚马逊账号，提醒玩家
    if isRemindConnectAmazon() then
        remindConnectAmazon();
        return false;
    end

    -- 计算完成度
    local requireProgress = query(id, "max_progress");
    local percent = string.format("%.2f", (count / requireProgress) * 100);

    -- 将请求投入到队列中
    appendRequest(gid, percent);

    -- 定时检查
    if not ScheduleM.isSchemeAlive("AmazonAchievementM") then
        ScheduleM.createScheme("AmazonAchievementM", checkRequest, CHECK_INTERVAL, true)
    end

    return true;
end

-- 将请求投入到队列中
function appendRequest(gid, percent)
    for i = 1, #requestQuene do
        local info = requestQuene[i];
        if info.gid == gid then
            -- 合并进度
            info.percent = info.percent + percent;
            return;
        end
    end

    table.insert(requestQuene, {["gid"] = gid, ["percent"] = percent });
end

-- 监测请求
function checkRequest()
    if #requestQuene == 0 then
        ScheduleM.deleteScheme("AmazonAchievementM");
        trace(PURE_FILE, "所有进度更新请求处理完毕。");
        return;
    end

    -- 处理队列中的第一条请求
    local info  = requestQuene[1];
    local gid   = info.gid;
    local percent = info.percent;

    trace(PURE_FILE, "处理进度更新请求：gid = %s, percent = %d", gid, percent);

    -- 调用sdk更新amazon成就进度
    if AmazonAgent then
        AmazonAgent.incrementAmazonAchievement(gid, percent);
    end

    table.remove(requestQuene, 1);
end

-- 是否绑定了亚马逊账号
function hasBoundAmazonAccount()
    local bindAccounts = AccountM.getBindAccounts();
    if #bindAccounts == 0 then
        return false;
    end

    for _, bindAccount in pairs(bindAccounts) do
        if string.startWith(bindAccount, CHANNEL_AMAZON) then
            return true;
        end
    end

    return false;
end

-- 是否提示登录亚马逊
function isRemindConnectAmazon()
    if get3rdAccountLoginInfo(CHANNEL_AMAZON) then
        -- 已经登录了亚马逊账号，无需提示
        return false;
    end

    local gamingAccount = getGaming3rdAccount() or "";
    if type(gamingAccount) ~= "string"  then
        return false;
    end

    if not string.startWith(gamingAccount, CHANNEL_AMAZON) and not hasBoundAmazonAccount() then
        -- 未绑定亚马逊账号
        return false;
    end

    local lastRemindTime = UserDefaultM.getStringForKey("LAST_REMIND_AMAZON_TIME");
    lastRemindTime = tonumber(lastRemindTime) or 0;
    if os.time() - lastRemindTime < REMIND_CD then
        -- 最近刚提醒过，暂时不提醒
        return false;
    end

    return true;
end

-- 提示玩家登录亚马逊
function remindConnectAmazon()
    EventMgr.fire(event.REMIND_CONNECT_AMAZON);
    UserDefaultM.setStringForKey("LAST_REMIND_AMAZON_TIME", tostring(os.time()));
end

-- 显示亚马逊成就列表
function displayAmazonAchievements()
    if AmazonAgent then
        AmazonAgent.displayAmazonAchievements();
    else
        alert(getLocStr("disable_function"));
    end
end




